// 注意: 请确保在common.js之前加载api.js
// <script src="js/api.js"></script>
// <script src="js/common.js"></script>

// 添加认证检查
function checkAuthentication() {
  // 同时从localStorage和cookie获取token
  const token = localStorage.getItem('token') || getCookie('token');
  const currentPath = window.location.pathname;
  // 使用相对路径或获取文件名进行比较
  const currentFileName = currentPath.split('/').pop();
  const loginFileName = 'login.html';
  const registerFileName = 'register.html'; // 添加注册页面文件名

  console.log('当前路径:', currentPath);
  console.log('当前文件名:', currentFileName);
  console.log('是否有token:', !!token);

  // 如果没有token且不是登录页面和注册页面，则跳转到登录页面
  if (!token && currentFileName !== loginFileName && currentFileName !== registerFileName) {
    window.location.href = 'login.html';
    return false;
  }

  // 如果有token且是登录页面或注册页面，则跳转到首页
  if (token && (currentFileName === loginFileName || currentFileName === registerFileName)) {
    window.location.href = 'index.html';
    return false;
  }

  return true;
}

// 初始化用户信息
function initUserInfo() {
  const userInfo = localStorage.getItem('userInfo');
  if (userInfo) {
    try {
      const user = JSON.parse(userInfo);
      const userElement = document.getElementById('user');
      const userRoleElement = document.getElementById('userRole');
      const userAvatarElement = document.getElementById('userAvatar');

      if (userElement) userElement.textContent = user.name || user.username;
      if (userRoleElement) userRoleElement.textContent = user.role || '普通用户';
      if (userAvatarElement) userAvatarElement.src = user.avatar || 'https://picsum.photos/200/200?random=1';

      // 根据角色初始化侧边栏
      initRoleBasedSidebar(user.role);
    } catch (error) {
      console.error('解析用户信息失败:', error);
    }
  }
}

// 根据角色初始化侧边栏
function initRoleBasedSidebar(role) {
  const sidebar = document.getElementById('sidebar');
  if (!sidebar) return;

  // 清空现有菜单
  const navUl = sidebar.querySelector('nav ul');
  if (!navUl) return;

  // 基础菜单
  let menuItems = [
    { href: 'index.html', icon: 'fa-dashboard', text: '仪表盘' },
  ];

  // 根据角色添加不同菜单
  if (role === 'admin') {
    menuItems = menuItems.concat([
      { href: 'employees.html', icon: 'fa-users', text: '员工管理' },
      { href: 'projects.html', icon: 'fa-briefcase', text: '项目管理' },
      { href: 'skill-management.html', icon: 'fa-cogs', text: '技能管理' },
      { href: 'reports.html', icon: 'fa-bar-chart', text: '分析报表' },
      { href: 'system-settings.html', icon: 'fa-cog', text: '系统设置' }
    ]);
  } else if (role === 'project_manager') {
    menuItems = menuItems.concat([
      { href: 'projects.html', icon: 'fa-briefcase', text: '项目管理' },
      { href: 'employees.html', icon: 'fa-users', text: '员工管理' },
      { href: 'skill-management.html', icon: 'fa-cogs', text: '技能管理' },
      { href: 'reports.html', icon: 'fa-bar-chart', text: '分析报表' }
    ]);
  } else {
    // 普通员工
    menuItems = menuItems.concat([
      { href: 'my-profile.html', icon: 'fa-user', text: '个人资料' },
      { href: 'projects.html', icon: 'fa-briefcase', text: '参与项目' },
      { href: 'leave-request.html', icon: 'fa-calendar', text: '请假申请' },
      { href: 'salary-history.html', icon: 'fa-money', text: '薪资历史' },
      { href: 'skill-management.html', icon: 'fa-cogs', text: '技能管理' }
    ]);
  }

  // 生成菜单HTML
  let menuHtml = '';
  menuItems.forEach(item => {
    const isActive = window.location.pathname.includes(item.href);
    menuHtml += `
      <li>
        <a href="${item.href}" class="sidebar-item ${isActive ? 'active' : ''}">
          <i class="fa ${item.icon}"></i>
          <span>${item.text}</span>
        </a>
      </li>
    `;
  });

  navUl.innerHTML = menuHtml;
}

// 检查用户角色权限
function checkRolePermission(requiredRoles) {
  const userInfo = localStorage.getItem('userInfo');
  if (!userInfo) return false;

  try {
    const user = JSON.parse(userInfo);
    return requiredRoles.includes(user.role);
  } catch (error) {
    console.error('解析用户信息失败:', error);
    return false;
  }
}

// 初始化登出功能
function initLogout() {
    const logoutBtn = document.getElementById('logoutBtn');
    if (logoutBtn) {
        logoutBtn.addEventListener('click', function() {
            if (confirm('确定要退出登录吗？')) {
                // 调用登出API
                api.logout()
                    .then(() => {
                        // 清除本地存储
                        localStorage.removeItem('token');
                        localStorage.removeItem('userInfo');
                        // 清除cookie
                        document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
                        // 跳转到登录页面
                        window.location.href = 'login.html';
                    })
                    .catch(error => {
                        console.error('登出失败:', error);
                        // 即使API失败，也清除本地存储并跳转
                        localStorage.removeItem('token');
                        localStorage.removeItem('userInfo');
                        document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
                        window.location.href = 'login.html';
                    });
            }
        });
    }
}

// 添加获取Cookie的辅助函数
function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) return parts.pop().split(';').shift();
    return null;
}

// 侧边栏切换
function initSidebar() {
  const sidebarToggle = document.getElementById('sidebarToggle');
  const sidebar = document.getElementById('sidebar');

  if (sidebarToggle && sidebar) {
    sidebarToggle.addEventListener('click', () => {
      sidebar.classList.toggle('hidden');
    });
  } else {
    console.warn('Sidebar elements not found in DOM');
  }
}

// 显示提示消息
function showToast(message, type = 'success') {
  // 创建toast元素
  const toast = document.createElement('div');
  // 使用有效的CSS类名，移除中括号
  toast.className = `fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg transform transition-all duration-500 ease-in-out z-50 opacity-0 translate-y-[-20px] ${
    type === 'success' ? 'bg-success text-white' : 'bg-danger text-white'
  }`;
  toast.textContent = message;

  // 添加到页面
  document.body.appendChild(toast);

  // 触发动画效果
  setTimeout(() => {
    toast.classList.remove('opacity-0', 'translate-y-[-20px]');
    toast.classList.add('opacity-100', 'translate-y-0');
  }, 10);

  // 3秒后移除
  setTimeout(() => {
    toast.classList.remove('opacity-100', 'translate-y-0');
    toast.classList.add('opacity-0', 'translate-y-[-20px]');

    setTimeout(() => {
      document.body.removeChild(toast);
    }, 500);
  }, 3000);
}

// 初始化页面
function initPage() {
  // 检查认证
  if (!checkAuthentication()) {
    return;
  }

  initSidebar();
  initUserInfo();
  initLogout();
  // 可以在这里添加更多初始化函数
}

// 检查axios是否已加载
function checkAxios() {
  if (typeof axios === 'undefined') {
    showToast('Error: axios library is not loaded', 'error');
    return false;
  }
  return true;
}

// API调用工具函数
async function apiRequest(url, method = 'GET', data = null, config = {}) {
    // 检查axios是否存在
    if (!checkAxios()) {
        throw new Error('axios library is not loaded');
    }

    try {
        const headers = {
            'Content-Type': 'application/json',
            ...config.headers
        };

        // 添加认证token (如果有)
        const token = localStorage.getItem('token') || getCookie('token');
        if (token) {
            headers['Authorization'] = `Bearer ${token}`;
        }

        // 如果数据是FormData，删除Content-Type，让浏览器自动设置
        if (data instanceof FormData) {
            delete headers['Content-Type'];
        } else if (data && typeof data !== 'string') {
            data = JSON.stringify(data);
        }

        const requestConfig = {
            url,
            method,
            headers,
            data,
            ...config
        };

        const response = await axios(requestConfig);
        return response.data;
    } catch (error) {
        // 处理401未授权错误
        if (error.response && error.response.status === 401) {
            showToast('登录已过期，请重新登录', 'error');
            localStorage.removeItem('token');
            localStorage.removeItem('userInfo');
            window.location.href = 'login.html';
            return;
        }

        // 处理403权限错误
        if (error.response && error.response.status === 403) {
            showToast('权限不足，请联系管理员', 'error');
            throw error;
        }

        // 其他错误处理
        const errorMessage = (error.response && error.response.data && error.response.data.message) || error.message || 'Unknown error';
        showToast(`请求失败: ${errorMessage}`, 'error');
        throw error;
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initPage);


// 显示加载中状态
function showLoading() {
  // 检查是否已存在加载元素
  let loadingElement = document.getElementById('loadingIndicator');
  if (!loadingElement) {
    loadingElement = document.createElement('div');
    loadingElement.id = 'loadingIndicator';
    loadingElement.className = 'fixed inset-0 bg-black/50 flex items-center justify-center z-50';
    loadingElement.innerHTML = `
      <div class="bg-white p-6 rounded-lg shadow-xl flex flex-col items-center">
        <div class="w-12 h-12 border-4 border-primary border-t-transparent rounded-full animate-spin"></div>
        <p class="mt-4 text-gray-700">加载中...</p>
      </div>
    `;
    document.body.appendChild(loadingElement);
  }
  loadingElement.style.display = 'flex';
}

// 隐藏加载中状态
function hideLoading() {
  const loadingElement = document.getElementById('loadingIndicator');
  if (loadingElement) {
    loadingElement.style.display = 'none';
  }
}